package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.Elevator;
import com.example.entity.ElevatorType;
import com.example.entity.PointDefend;
import com.example.entity.PointFlow;
import com.example.entity.authority.Party;
import com.example.ext.entity.ExtElevator;
import com.example.ext.entity.ExtSysUser;
import com.example.mapp.*;
import com.example.service.ElevatorService;
import com.example.service.StatisticsService;
import com.example.service.SysUserService;
import com.example.util.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by youkun on 2017/10/5.
 * 电梯信息
 */
@Service
public class ElevatorServiceImpl implements ElevatorService{

    private final static Logger logger = (Logger) LoggerFactory.getLogger(ElevatorServiceImpl.class);

    @Autowired
    private ElevatorMapp elevatorMapp;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ElevatorTypeMapp elevatorTypeMapp;

    @Autowired
    private PartyMapp partyMapp;

    @Autowired
    private SysUserMapp sysUserMapp;

    @Autowired
	private PromotionMapp promotionMapp;
    
    @Autowired
	private ImportRecordMapp importRecordMapp;

    @Autowired
    private PointFlowMapp pointFlowMapp;

    @Autowired
    private StatisticsService statisticsServiceImp;
    
    @Override
    public Map<String, Object> queryList(ExtElevator elevator) {
        List<ExtElevator> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtElevator> page = PageHelper.startPage(elevator.getCurrentPage(), elevator.getPageSize());
            list = elevatorMapp.queryList(elevator);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    @Override
    public Map<String, Object> queryMaintList(Map<String, Object> elevator) {
        List<ExtElevator> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtElevator> page = PageHelper.startPage(Integer.parseInt(elevator.get("currentPage")+""), Integer.parseInt(elevator.get("pageSize")+""));
            list = elevatorMapp.queryMaintList(elevator);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    @Override
    public Map<String, Object> queryJgList(Map<String, Object> elevator) {
        List<ExtElevator> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtElevator> page = PageHelper.startPage(Integer.parseInt(elevator.get("currentPage")+""), Integer.parseInt(elevator.get("pageSize")+""));
            list = elevatorMapp.queryJgList(elevator);
            map.put("list",list);
            map.put("total",page.getTotal());

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    @Override
    @Transactional
    public Map<String, Object> add(Elevator elevator) {

        //TODO 暂时封起来 不允许手动添加
        return ResultUtil.returnError("不允许手动添加",null);

//        try {
//            Elevator sys = elevatorMapp.queryByElevatorNum(elevator.getElevatorNum());
//            if(null==sys){
//                elevator.setPointsNum("0");
//                elevatorMapp.add(elevator);
//                //生成电梯的二位码
//               Map<String,Object> map =  sysUserService.createQrcode(elevator.getId().toString(),elevator.getElevatorTypeId().toString(),elevator.getElevatorNum().toString(),elevator.getUsedPartyId()+"");
//               if(map.get("status").toString().equals("200")){
//                   elevator.setQrCodeUrl(((Map)map.get("data")).get("imagePath")+"");
//                   elevator.setUrl(((Map)map.get("data")).get("urlPath")+"");
//               }
//                //更新
//                elevatorMapp.update(elevator);
//            }else {
//                throw new Exception(elevator.getElevatorNum()+"已存在!");
//            }
//
//        }catch (Exception e){
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            logger.error(e.getMessage());
//            return ResultUtil.returnError(e.getMessage(),null);
//        }
//        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> update(Elevator elevator) {
        Elevator updateBefore = null;
        try {
            //查询数据是否存在
            Elevator system = elevatorMapp.queryById(elevator.getId().toString());
            if(null==system){
                throw new Exception("数据不存在!");
            }
//            updateBefore = system;

            if(elevator.getElevatorNum().equals(system.getElevatorNum())){
                elevatorMapp.update(elevator);
            }else{
                Elevator sys = elevatorMapp.queryByElevatorNum(elevator.getElevatorNum());
                if(null==sys){
                    elevator.setQrCodeUrl(system.getQrCodeUrl());
                    elevatorMapp.update(elevator);
                }else {
                    throw new Exception(elevator.getElevatorNum()+"已存在!");
                }
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }finally {
            if ("2".equals(elevator.getLoggerType()) && "16".equals(elevator.getRoleId())) {
                // 电梯修改，回影响占比
                PointDefendInfoCache infoCache = new PointDefendInfoCache();
                PointDefend pointDefend = infoCache.getKeyByValue("add_elevator_info");

                if (pointDefend != null) {
                    // 获取必填字段
                    List<String> strings = Arrays.asList(pointDefend.getMustBean().split(","));
                    double rate = ObjectBeanUtils.percentage(elevator, strings);
                    if (rate != 0) {
                        // 单个电梯的积分
                        int round = (int) (rate * pointDefend.getMark());
                        // 当照片进行更新后，加10分
                        String message = "";

                        // 先将单个电梯的积分清空，然后再将新的积分更新
                        elevator.setMark(round);
                        elevatorMapp.updateMark(elevator);
                        // 计算单位下所有的电梯积分，得到单位总积分
                        Map sumMark = elevatorMapp.getSumMark(elevator.getUsedPartyId().toString());
                        int allElevator = Integer.parseInt(sumMark.get("mark")+"");
                        // 查询角色信息得到单位总积分
                        Map<String, Object> maps = pointFlowMapp.findUserInfo(elevator.getUsedPartyId());
                        long mark = (long) maps.get("mark");

                        // 查询流水表里是否有记录了，如果有删除掉，再加
                        PointFlow pointFlow = new PointFlow();
                        pointFlow.setIdentification("add_elevator_info");
                        List<PointFlow> flowlist = pointFlowMapp.findOne(pointFlow);
                        if (flowlist != null && flowlist.size() > 0) {
                            round = (int) ((mark - flowlist.get(0).getMark()) + allElevator);
                        } else {
                            round = (int) (mark + allElevator);
                        }
                        // 更新单位总积分
                        String userId = (String) maps.get("userId");
                        int i1 = pointFlowMapp.updateMark(round, userId);
                        // 插入流水
                        String userName = (String) maps.get("userName");
                        String partyName = (String) maps.get("partyName");
                        String function = "修改电梯" + message;
                        SystemPointUtil.insertFlow(pointFlowMapp, i1, pointDefend, allElevator, userName, partyName, function);

                        // 添加安全管理员的积分
                        PointDefend pointUserDefend = infoCache.getKeyByValue("add_elevator_info_user");
                        Map<String, Object> usermaps = pointFlowMapp.findUserInfoByUserId(Long.valueOf(elevator.getLoggerUserId()));

                        // 计算分数
                        int roundUsers = (int) (rate * pointUserDefend.getMark());

                        // 判断原来的分数是否为 0
                        long markUsers = (long) usermaps.get("mark");
                        if(markUsers != 0){
                            // 通过唯一标识查询流水表获取上一次积分，然后减去
                            PointFlow pointUserFlow = new PointFlow();
                            pointUserFlow.setIdentification("add_elevator_info_user");
                            List<PointFlow> list = pointFlowMapp.findOne(pointUserFlow);
                            if (list != null && list.size() > 0) {
                                roundUsers = (int) ((markUsers - list.get(0).getMark()) + roundUsers);
                            } else {
                                roundUsers = (int) (markUsers + roundUsers);
                            }
                        }
                        int i2 = pointFlowMapp.updateMark(roundUsers, elevator.getLoggerUserId());
                        String userName2 = "电梯安全管理员";
                        String partyName2 = (String) maps.get("partyName");
                        SystemPointUtil.insertFlow(pointFlowMapp,i2,pointUserDefend,roundUsers,userName2,partyName2,"建立电梯台账、录入电梯使用登记信息");
                    }
                }
            }
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> updatehmMaintDate(Map<String,Object> inMap) {
        try {
            String date = (new SimpleDateFormat("yyyyMMdd")).format(new Date());
            inMap.put("lastMaintenanceTime",date);
            /**
             * 判断是否参数按需维保，获取维保天数
             */
            ExtElevator elevator = new ExtElevator();
            elevator.setElevatorNum(inMap.get("elevatorNum")+"");
            List<ExtElevator> extElevators = elevatorMapp.queryList(elevator);
            String isParticipateIn = "";
            int addDay = 0;
            if(extElevators != null && extElevators.size() != 0){
                isParticipateIn =  extElevators.get(0).getIsParticipateIn();
                addDay = extElevators.get(0).getMaintenanceDay();
                if(!"1".equals(isParticipateIn) || addDay == 0){
                    addDay = 15;
                }
            }
            Calendar calendar2 = Calendar.getInstance();
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");

            calendar2.add(Calendar.DATE, addDay);
            String dd= sdf2.format(calendar2.getTime());
            inMap.put("nextHalfmonMaintDate",dd);

            elevatorMapp.updatehmMaintDate(inMap);

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> updateqMaintDate(Map<String,Object> inMap) {
        try {
            String date = (new SimpleDateFormat("yyyyMMdd")).format(new Date());
            inMap.put("lastMaintenanceTime",date);

            Calendar calendar2 = Calendar.getInstance();
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
            calendar2.add(Calendar.DATE, 90);
            String dd= sdf2.format(calendar2.getTime());
            inMap.put("nextQuarterlyMainteDate",dd);

            elevatorMapp.updateqMaintDate(inMap);

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> updatehyMaintDate(Map<String,Object> inMap) {
        try {
            String date = (new SimpleDateFormat("yyyyMMdd")).format(new Date());
            inMap.put("lastMaintenanceTime",date);

            Calendar calendar2 = Calendar.getInstance();
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
            calendar2.add(Calendar.DATE, 180);
            String dd= sdf2.format(calendar2.getTime());
            inMap.put("nextHalfyearMaintDate",dd);

            elevatorMapp.updatehyMaintDate(inMap);

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> updateyMaintDate(Map<String,Object> inMap) {
        try {
            String date = (new SimpleDateFormat("yyyyMMdd")).format(new Date());
            inMap.put("lastMaintenanceTime",date);

            Calendar calendar2 = Calendar.getInstance();
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
            calendar2.add(Calendar.DATE, 360);
            String dd= sdf2.format(calendar2.getTime());
            inMap.put("nextYearMaintDate",dd);

            elevatorMapp.updateyMaintDate(inMap);

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    public Map<String, Object> updateLatLng(Map<String,Object> inMap){
        try {

            elevatorMapp.updateLatLng(inMap);

        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    @Transactional
    public Map<String, Object> importElevator(MultipartFile file, String partyId) {
        try {
            List<List<Object>> list = ExcelUtil.getListByExcel(file.getInputStream(),file.getOriginalFilename());
            //获取导入的信息做处理
            if(list!=null && list.size()>0){
                for(int i=0;i<list.size();i++){
                    List listObject = list.get(i);
                    if(listObject!=null && listObject.size()>6){
                        if((listObject.get(0)+"").equals("序号") || "".equals(listObject.get(2))){
                            continue;
                        }
                        Elevator elevator = new Elevator();
                        //物业id
                        elevator.setUsedPartyId(Long.parseLong(partyId));
                        //安装地点
                        if(listObject.get(1)!=null && !listObject.get(1).equals("")){
                            elevator.setBuildAddr(listObject.get(1).toString());
                        }
                       // 设备类型,
                        if(listObject.get(2)!=null && !"".equals(listObject.get(2)+"")){
                          ElevatorType elevatorType =  elevatorTypeMapp.queryByTypeName(listObject.get(2).toString());
                          if(elevatorType==null){
                              throw new Exception("设备类型:'"+listObject.get(2).toString()+"'不存在");
                          }
                          elevator.setElevatorTypeId(elevatorType.getId());
                        }else{
                            //continue;
                            throw new Exception(listObject.get(4)+" 的设备类型不能为空!");
                        }
                        // 设备型号,
                        if(listObject.get(3)!=null && !"".equals((listObject.get(3)+"").trim())){
                            elevator.setElevatorModel(listObject.get(3)+"");
                        }
                        // 注册代码,
                        if(listObject.get(4)!=null&& !"".equals((listObject.get(4)+"").trim())){
                            Elevator sys = elevatorMapp.queryByElevatorNum(listObject.get(4)+"");
                            if(sys!=null){
                                continue;
                            }else{
                                elevator.setElevatorNum(listObject.get(4).toString());
                            }
                        }else{
                            throw new Exception("设备注册代码不能为空！");
                        }
                        // 使用证号,
                        if(listObject.get(5)!=null){
                            elevator.setUsedNum(listObject.get(5).toString());
                        }
                        // 投用日期,
                        if(listObject.get(6)!=null && !"".equals(listObject.get(6)+"")){

                            if((listObject.get(6)+"").contains("-")){
                                elevator.setBeUsedDate(listObject.get(6).toString().replaceAll("-",""));
                            }else{
                                elevator.setBeUsedDate(listObject.get(6).toString().split("\\.")[0]);
                            }
                        }
                        // 年检日期,
                        if(listObject.get(7)!=null && !"".equals(listObject.get(7)+"")){
                            if((listObject.get(7)+"").contains("-")){
                                elevator.setNextCheckDate(listObject.get(7).toString().replaceAll("-",""));
                            }else{
                                elevator.setNextCheckDate(listObject.get(7).toString().split("\\.")[0]);
                            }

                        }
                        // 限速器检验日期,
                        if(listObject.get(8)!=null && !"".equals(listObject.get(8)+"")){
                            if((listObject.get(8)+"").contains("-")){
                                elevator.setGovernorCkDate(listObject.get(8).toString().replaceAll("-",""));
                            }else{
                                elevator.setGovernorCkDate(listObject.get(8).toString().split("\\.")[0]);
                            }
                        }
                        // 层/站,
                        if(listObject.get(9)!=null){
                            elevator.setFloorStation(listObject.get(9).toString());
                        }
                        // 使用状况
                        if(listObject.get(10)!=null){
                            //0在用  1停用 2安装 3注销
                            if(listObject.get(10).toString().equals("在用")){
                                elevator.setIsStop("0");
                            }else
                            if(listObject.get(10).toString().equals("停用")){
                                elevator.setIsStop("1");
                            }else
                            if(listObject.get(10).toString().equals("安装")){
                                elevator.setIsStop("2");
                            }else
                            if(listObject.get(10).toString().equals("注销")){
                                elevator.setIsStop("3");
                            }else{
                                throw  new Exception("使用状况有：在用，停用，安装，注销请填写正确");
                            }

                        }
                        // , 安全管理员
                        if(listObject.get(11)!=null){
                            ExtSysUser extSysUser = new ExtSysUser();
                            extSysUser.setPartyId(Long.parseLong(partyId));
                            extSysUser.setUserName(listObject.get(11).toString());
                            List<ExtSysUser> systemUserList = sysUserMapp.findUserByPartyIdAndUserName(extSysUser);
                            if(systemUserList!=null && systemUserList.size()>0){
                                elevator.setSafeUserId(systemUserList.get(0).getId());
                            }

                        }
                        // , 联系电话,
                        if(listObject.get(12)!=null){
                            elevator.setSafeUserTel(listObject.get(12).toString());
                        }
                        // 维保单位,
                        if(listObject.get(13)!=null){
                            Party sl = new Party();
                            sl.setPartyType("1");
                            sl.setPartyName(listObject.get(13).toString().trim());
                            Party party =  partyMapp.queryByPartyTypeAndName(sl);
                           if(party!=null){
                               elevator.setMaintenancePartyId(party.getId());
                               PromotionUtil.calcParty(promotionMapp, 1, "1", party.getId(), "上传电梯台账", "0");

                           }

                        }
                        // 维保人员,
                        if(listObject.get(14)!=null){
                            ExtSysUser extSysUser = new ExtSysUser();
                            extSysUser.setPartyId(elevator.getMaintenancePartyId());
                            extSysUser.setUserName(listObject.get(14).toString());
                            List<ExtSysUser> systemUserList = sysUserMapp.findUserByPartyIdAndUserName(extSysUser);
                            if(systemUserList!=null && systemUserList.size()>0){
                                elevator.setSafeUserId(systemUserList.get(0).getId());
                            }

                        }
                        //联系电话,
                        if(listObject.get(15)!=null){
                            elevator.setMaintTel(listObject.get(15).toString());
                        }
                        // 额定载荷,
                        if(listObject.get(16)!=null){
                            elevator.setRatedLoad(listObject.get(16).toString());
                        }
                        // 运行速度,
                        if(listObject.get(17)!=null){
                            elevator.setRunSpeed(listObject.get(17).toString());
                        }
                        // 出厂编号,
                        if(listObject.get(18)!=null){
                            elevator.setSerialNum(listObject.get(18).toString());
                        }
                        // 制造单位,
                        if(listObject.get(19)!=null){
                            elevator.setCreateCompanyName(listObject.get(19).toString());
                        }
                        // 安装单位,
                        if(listObject.get(20)!=null){
                            elevator.setBuildPartyName(listObject.get(20).toString());
                        }
                        // 电梯安全责任保险投保单位名称,
                        if(listObject.get(21)!=null){
                            elevator.setInsuranceName(listObject.get(21).toString());
                        }
                        // 电梯安全责任保险到期日期,
                        if(listObject.get(22)!=null && !"".equals(listObject.get(22)+"")){

                            if((listObject.get(22)+"").contains("-")){
                                elevator.setInsuranceDate(listObject.get(22).toString().replaceAll("-",""));
                            }else{
                                elevator.setInsuranceDate(listObject.get(22).toString().split("\\.")[0]);
                            }
                        }
                        // 载重/角度,
                        if(listObject.get(23)!=null){
                            elevator.setAngle(listObject.get(23).toString());
                        }
                        // 梯级宽度,
                        if(listObject.get(24)!=null){
                            elevator.setStepWidth(listObject.get(24).toString());
                        }
                        // 提升高度,
                        if(listObject.get(25)!=null){
                            elevator.setLiftHeight(listObject.get(25).toString());
                        }
                        //上次维保时间
                        if(listObject.get(26)!=null && !"".equals(listObject.get(26)+"")){
                            if((listObject.get(26)+"").contains("-")){
                                elevator.setLastMaintenanceTime(listObject.get(26).toString().replaceAll("-",""));
                            }else{
                                elevator.setLastMaintenanceTime(listObject.get(26).toString().split("\\.")[0]);
                            }
                        }
                        // 下次半月保时间,
                        if(listObject.get(27)!=null && !"".equals(listObject.get(27)+"")){
                            if((listObject.get(27)+"").contains("-")){
                                elevator.setNextHalfmonMaintDate(listObject.get(27).toString().replaceAll("-",""));
                            }else{
                                elevator.setNextHalfmonMaintDate(listObject.get(27).toString().split("\\.")[0]);
                            }
                        }
                        // 下次季度保时间,
                        if(listObject.get(28)!=null && !"".equals(listObject.get(28)+"")){
                            if((listObject.get(28)+"").contains("-")){
                                elevator.setNextQuarterlyMainteDate(listObject.get(28).toString().replaceAll("-",""));
                            }else{
                                elevator.setNextQuarterlyMainteDate(listObject.get(28).toString().split("\\.")[0]);
                            }
                        }
                        // 下次半年保时间,
                        if(listObject.get(29)!=null && !"".equals(listObject.get(29)+"")){
                            if((listObject.get(29)+"").contains("-")){
                                elevator.setNextHalfyearMaintDate(listObject.get(29).toString().replaceAll("-",""));
                            }else{
                                elevator.setNextHalfyearMaintDate(listObject.get(29).toString().split("\\.")[0]);
                            }
                        }
                        // 下次年保时间,
                        if(listObject.get(30)!=null && !"".equals(listObject.get(30)+"")){
                            if((listObject.get(30)+"").contains("-")){
                                elevator.setBeUsedDate(listObject.get(30).toString().replaceAll("-",""));
                            }else{
                                elevator.setBeUsedDate(listObject.get(30).toString().split("\\.")[0]);
                            }
                        }
                        // 救援电话,
                        if(listObject.get(31)!=null){
                            elevator.setRescuePhoneNum(listObject.get(31).toString());
                        }
                        // 外部关联码
                        if(listObject.get(32)!=null){
                            elevator.setOutsideNum(listObject.get(32).toString());
                        }

                        //后来添加的电梯品牌添加到最后
                        if(listObject.get(33)!=null){
                            elevator.setBrandName(listObject.get(33).toString());
                        }
                        if(listObject.get(34) != null){ //检验人员1 （暂时没有检验模块）

                        }
                        if(listObject.get(35) != null){ //检验人员2

                        }
                        if(listObject.get(36) != null){//内部编号
                            elevator.setInnerId(listObject.get(36).toString());
                        }
                        if(listObject.get(37) != null){//上次巡检时间
                            if((listObject.get(37)+"").contains("-")){
                                elevator.setBeUsedDate(listObject.get(37).toString().replaceAll("-",""));
                            }else{
                                elevator.setBeUsedDate(listObject.get(37).toString().split("\\.")[0]);
                            }
                        }
                        if(listObject.get(38) != null){//项目名称
                            elevator.setProgramName(listObject.get(38).toString());
                        }
                        if(listObject.get(39) != null){//所属分局
                            Party party = new Party();
                            party.setPartyType("4");
                            party.setPartyName(listObject.get(39).toString().trim());
                            Party result =  partyMapp.queryByPartyTypeAndName(party);
                            if(result != null){
                                elevator.setBranchOffice(result.getId().toString());
                            }
                        }
                        if(listObject.get(40) != null){//场所类型
                            elevator.setPlaceType(listObject.get(40).toString());
                        }
                        if(listObject.get(41) != null){//场所名称
                            elevator.setElevatorPlace(listObject.get(41).toString());
                        }
                        if(listObject.get(42) != null){//检验单位名称
                            elevator.setExaminationPartyName(listObject.get(42).toString());
                        }
                        if(listObject.get(43) != null){//电梯驱动方式
                            elevator.setDriveWay(listObject.get(43).toString());
                        }

                        //插入电梯
                        elevator.setPointsNum("0");
                        elevatorMapp.add(elevator);


                        Map<String,Object> map =  sysUserService.createQrcode(elevator.getId().toString(),elevator.getElevatorTypeId().toString(),elevator.getElevatorNum().toString(),partyId);
                        if(map.get("status").toString().equals("200")){
                            elevator.setQrCodeUrl(((Map)map.get("data")).get("imagePath")+"");
                            elevator.setUrl(((Map)map.get("data")).get("urlPath")+"");
                        }
                        //更新
                        elevatorMapp.update(elevator);

                        // 电梯批量操作后，进行积分计算
                        // 获取缓存数据
                        PointDefendInfoCache infoCache = new PointDefendInfoCache();
                        PointDefend pointDefend = infoCache.getKeyByValue("add_elevator_info");
                        if (pointDefend != null) {
                            // 获取必填字段
                            List<String> strings = Arrays.asList(pointDefend.getMustBean().split(","));
                            double rate = ObjectBeanUtils.percentage(elevator, strings);
                            if (rate != 0) {
                                // 单个电梯的积分
                                int round = (int) (rate * pointDefend.getMark());
                                // 先将单个电梯的积分清空，然后再将新的积分更新
                                elevator.setMark(round);
                                elevatorMapp.updateMark(elevator);
                                // 计算单位下所有的电梯积分，得到单位总积分
                                Map sumMark = elevatorMapp.getSumMark(partyId);
                                int allElevator = Integer.parseInt(sumMark.get("mark")+"");
                                // 查询角色信息得到单位总积分
                                Map<String, Object> maps = pointFlowMapp.findUserInfo(Long.valueOf(partyId));
                                long mark = (long) maps.get("mark");

                                // 查询流水表里是否有记录了，如果有删除掉，再加
                                PointFlow pointFlow = new PointFlow();
                                pointFlow.setIdentification("add_elevator_info");
                                List<PointFlow> flowlist = pointFlowMapp.findList(pointFlow);
                                if (flowlist != null && flowlist.size() > 0) {
                                    round = (int) ((mark - flowlist.get(0).getMark()) + allElevator);
                                }else{
                                    round = (int) (mark + allElevator);
                                }
                                // 更新单位总积分
                                String userId = (String) maps.get("userId");
                                int i1 = pointFlowMapp.updateMark(round, userId);
                                // 插入流水
                                String userName = (String) maps.get("userName");
                                String partyName = (String) maps.get("partyName");
                                String function = "新增电梯";
                                SystemPointUtil.insertFlow(pointFlowMapp, i1, pointDefend, allElevator, userName, partyName, function);

                            }
                        }
                    }
                }
                // 旧版积分进行删除
                /*PromotionUtil.calcParty(promotionMapp, list.size()*5, "2", Long.valueOf(partyId), "上传电梯台账", "0");

                ImportRecord importRecord = new ImportRecord();
                importRecord.setUserId(partyId);
                importRecord.setType("2");
                int num = importRecordMapp.findByIdList(importRecord);
                if (num == 0) {
                	importRecord.setImportDt(new SimpleDateFormat("yyyyMMdd").format(new Date()));
                	importRecordMapp.add(importRecord);
                	PromotionUtil.calcParty(promotionMapp, 30, "2", Long.valueOf(partyId), "上传1次电梯台账", "0");
                }*/
            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error("上传电梯失败："+e.getMessage(),e);
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }


    @Override
    @Transactional
    public Map<String, Object> delete(List<String> ids) {
        try {
            PointDefendInfoCache infoCache = new PointDefendInfoCache();
            PointDefend pointDefend = infoCache.getKeyByValue("add_elevator_info");
            for(int i=0;i<ids.size();i++){

                // 先获取单位Id
                ExtElevator extElevator = elevatorMapp.queryById(ids.get(i));
                elevatorMapp.deleteById(ids.get(i));

                // 查询角色信息得到单位总积分
                Map<String, Object> maps = pointFlowMapp.findUserInfo(extElevator.getUsedPartyId());
                long mark = (long) maps.get("mark");

                int round = (int) (mark - pointDefend.getMark());

                // 更新单位总积分
                String userId = (String) maps.get("userId");
                int i1 = pointFlowMapp.updateMark(round, userId);

                // 插入流水
                String userName = (String) maps.get("userName");
                String partyName = (String) maps.get("partyName");
                String function = "删除电梯";
                SystemPointUtil.insertFlow(pointFlowMapp, i1, pointDefend, round, userName, partyName, function);

            }
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            logger.error(e.getMessage());
            return ResultUtil.returnError("失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> queryById(String id) {
        ExtElevator elevator = null;
        try {
            elevator = elevatorMapp.queryById(id);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",elevator);
    }

    @Override
    public Map<String, Object> getLatLng(Map<String,Object> inMap){
        String partyId = Integer.toString((Integer) inMap.get("partyId"));
        List<Map> elevator = null;
        try {
            String mark = statisticsServiceImp.decideInfo(partyId);
            elevator = elevatorMapp.getLatLng(inMap,mark);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",elevator);

    }

    @Override
    public Map<String, Object> updateElevatorPlace(Map<String, Object> inMap) {
        try {
            elevatorMapp.updateElevatorPlace(inMap);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("更新失败",null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String, Object> updateSafeUser(Map<String, Object> inMap) {
        try {
            elevatorMapp.updateSafeUser(inMap);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("更新失败",null);
        }
        return ResultUtil.returnSuccess("成功",null);
    }

    @Override
    public Map<String,Object> getElevatorInfoByNum(Map<String, Object> param) {
        ExtElevator elevator = null;
        try {
            elevator = elevatorMapp.getElevatorInfoByNum(param);
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError(e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("成功",elevator);
    }

    /**
     * 双随机一公开查询电梯信息
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> getElevatorList(Map<String, Object> param) {
        String message = "查询成功";
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            // 获取过滤后的参数
            Map<String, Object> filterParam = param;

            int currentPage = (int) param.get("currentPage");
            int pageSize = (int) param.get("pageSize");
            if (StringUtil.isNotBlank(currentPage+"") && StringUtil.isNotBlank(pageSize+"") ) {
                Page<Map<String,Object>> page = PageHelper.startPage(currentPage, pageSize);

                if (param.get("elevatorPlaceParam") != null) {
                    String elevatorPlaceParam = param.get("elevatorPlaceParam").toString();
                    if (StringUtil.isNotBlank(elevatorPlaceParam)) {
                        List<String> place = Arrays.asList(elevatorPlaceParam.split(","));
                        param.put("elevatorPlaceParam", place);

                        filterParam.put("elevatorPlaceParam", place);
                    }
                }
                List<Map<String, Object>> list = elevatorMapp.getElevatorList(param);
                List<Map<String, Object>> lists = elevatorMapp.getElevatorList(filterParam);
                Map<String, Object> paramList = new HashMap<>();
                if (lists != null && lists.size() > 0) {
                    for (Map<String, Object> objectMap : lists) {
                        String usedPartyId = objectMap.get("usedPartyId").toString();
                        if (paramList.containsKey(usedPartyId)) {
                            continue;
                        } else {
                            paramList.put(usedPartyId, objectMap);
                        }
                    }
                }
                List<Map<String, Object>> unitlist = new ArrayList<>();
                if (paramList != null && paramList.size() > 0) {
                    for (Map.Entry<String, Object> object : paramList.entrySet()) {
                        unitlist.add((Map<String, Object>) object.getValue());
                    }
                }
                map.put("list", list);
                map.put("total", page.getTotal());
                map.put("unitlist",unitlist);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            message = "查询失败";
            return ResultUtil.returnError(message + e.getMessage(), map);
        }
        return ResultUtil.returnSuccess(message, map);
    }

    @Override
    public Map<String, Object> demandMaintGetElevators(ExtElevator elevator) {

        List<ExtElevator> list =null;
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            Page<ExtElevator> page = null;
            if(elevator.getCurrentPage() != null){
                page = PageHelper.startPage(elevator.getCurrentPage(), elevator.getPageSize());
            }

            list = elevatorMapp.demandMaintGetElevators(elevator);
            map.put("list",list);
            if(elevator.getCurrentPage() != null){
                map.put("total",page.getTotal());
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }

    @Override
    public Map<String, Object> queryCreateCompanys(ExtElevator elevator) {
        List<String> list = null;
        Map<String,Object> map = new HashMap<>();
        try{
            list = elevatorMapp.queryCreateCompanys(elevator);
            map.put("list",list);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            return ResultUtil.returnError("查询失败"+e.getMessage(),null);
        }
        return ResultUtil.returnSuccess("查询成功",map);
    }


}
